CONTENTS | INDEX | PREV | NEXT
fread
NAME
fread - read data from a file pointer
SYNOPSIS
#include <stdio.h>
size_t robjs = fread(buf, objsize, nobjs, fp);
void *buf;
size_t objsize;
size_t nobjs;
FILE *fp;
FUNCTION
fread() reads an arbitrary number of objects from a file pointer
into the specified buffer and returns the actual number of objects
read.
If the return value robjs is not equal to nobjs then fread() was
unable to read the requested number of objects due to either a
read error or EOF condition. If the file is already completely
exhausted fread() simply returns 0.
Having two size arguments, an object size and number of objects,
simplifies the reading of structure arrays off disk.
NOTE
To use fread to read an arbitrary number of bytes one normally
uses the form: r = fread(buf, 1, n, fp); ... i.e. n objects
of size 1.
fread() will attempt to read objsize * nobjs bytes into the
specified buffer.
EXAMPLE
/*
* NOTE: run fwrite() example before running this example
* to create the dummy file.
*/
#include <stdio.h>
#define NOBJS 10
typedef struct {
short a, b, c, d;
} MyObj;
main()
{
FILE *fp;
static MyObj Obj[NOBJS];
if (fp = fopen("T:fwrite_tmp", "rb")) {
short n;
while ((n = fread(Obj, sizeof(MyObj), NOBJS, fp)) > 0) {
short i;
for (i = 0; i < n; ++i) {
printf("a = %-5d b = %-5d c = %-5d d = %-5dn",
Obj[i].a, Obj[i].b, Obj[i].c, Obj[i].d
);
}
}
fclose(fp);
} else {
puts("Unable to open T:fwrite_tmp, run fwrite example first");
exit(1);
}
return(0);
}
INPUTS
void *buf; buffer to load data into
size_t objsize; size of one object
size_t nobjs; number of objects to read
FILE *fp; file pointer to read objects from
RESULTS
size_t robjs; number of objects actually read or 0 if EOF or ERROR.
SEE ALSO
fwrite, fopen, fclose, fseek, ftell, rewind